﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Base;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.ServiceProject;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class ServiceProjectController : BaseController
    {
        #region 服务项目页面 + ActionResult ServiceProjectIndex()
        public ActionResult ServiceProjectIndex()
        {
            return View();
        }
        #endregion

        #region 服务项目管理页面获取列表数据 + ActionResult ServiceProjectList(ServiceProjectModel model)
        /// <summary>
        /// 服务项目管理页面获取列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult ServiceProjectList(ServiceProjectModel model)
        {
            var total = 0;
            var list = ServiceFactory.ServiceProjectServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList()
                .Select(a => new
                {
                    a.ID,
                    ServiceProductTypeName = EnumHelper.Instance.GetDescription(typeof(ServiceProductType), a.ServiceProductType),
                    a.ProjectName,
                    a.ProjectCode,
                    a.UnitInstruction,
                    a.Price,
                    a.IsAvailable,
                    a.LastModifyBy,
                    a.LastModifyTime,
                });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 服务项目编辑 + ActionResult ServiceProjectEdit(int id)
        /// <summary>
        /// 服务项目编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult ServiceProjectEdit(int id)
        {
            ViewBag.ShowTitle = id > 0 ? "编辑服务项目" : "添加服务项目";
            var ServiceProject = ServiceFactory.ServiceProjectServiceInstance.LoadByID(id);
            return View(ServiceProject);
        }

        #endregion

        #region 保存服务项目 + ActionResult SaveServiceProject(ServiceProject model)

        [HttpPost]
        [ValidateInput(false)]
        //保存服务项目
        public ActionResult SaveServiceProject(ServiceProject model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };

            var serv = ServiceFactory.ServiceProjectServiceInstance;
            model.ProjectName = model.ProjectName.Trim();
            //新增
            if (model.ID == 0)
            {
                if (serv.IsExist(model.ProjectName))
                {
                    responseResult.Message = "该服务项目已经存在";
                    TempData["ResponseResult"] = responseResult;
                    return RedirectToAction("ServiceProjectEdit", new { id = model.ID });
                }
                else
                {
                    model.CreateTime = DateTime.Now;
                    model.CreateBy = CurrentUser.UserAccount;
                    model.LastModifyBy = CurrentUser.UserAccount;
                    model.LastModifyTime = DateTime.Now;
                    using (TransactionScope ts = new TransactionScope())
                    {
                        var entity = serv.AddEntities(model);
                        responseResult.Success = entity.ID > 0;
                        if (!responseResult.Success) //设置项目编码
                        {
                            ts.Dispose();
                            TempData["ResponseResult"] = responseResult;
                            return RedirectToAction("ServiceProjectEdit", new { id = model.ID });
                        }
                        string code = CommonMethod.GenerateCode("FWXM", entity.ID.ToString(), 6);
                        entity.ProjectCode = code;
                        if (!serv.UpdateEntities(entity))
                        {
                            ts.Dispose();
                            responseResult.Message = "新增失败，设置服务项目编码失败";
                            TempData["ResponseResult"] = responseResult;
                            return RedirectToAction("ServiceProjectEdit", new { id = model.ID });
                        }
                        ts.Complete();
                    }
                }
            }
            //修改
            else
            {
                var entity = serv.LoadByID(model.ID);
                if (entity != null)
                {
                    if (serv.IsExist(model.ProjectName, model.ID))
                    {
                        responseResult.Message = "已存在同名的服务项目，请修改服务项目名称";
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("ServiceProjectEdit", new { id = model.ID });
                    }
                    entity.ProjectName = model.ProjectName;
                    entity.Price = model.Price;
                    entity.UnitInstruction = model.UnitInstruction;
                    entity.ProjectDescribe = model.ProjectDescribe;
                    entity.IsAvailable = model.IsAvailable;
                    entity.LastModifyBy = CurrentUser.UserAccount;
                    entity.LastModifyTime = DateTime.Now;
                    responseResult.Success = ServiceFactory.ServiceProjectServiceInstance.UpdateEntities(entity);
                }
                else
                {
                    responseResult.Message = "该服务项目不存在或已被删除";
                }
            }
            TempData["ResponseResult"] = responseResult;
            return responseResult.Success ? RedirectToAction("ServiceProjectIndex") : RedirectToAction("ServiceProjectEdit", new { id = model.ID });
        }


        #endregion

        #region 禁用/启用服务项目 + JsonResult UpdateStatus(int id, bool isAvailable)
        /// <summary>
        /// 禁用/启用服务项目
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="isAvailable">启用/禁用</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.ServiceProjectServiceInstance.LoadByID(id);
            var success = false;
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.ServiceProjectServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion

        #region 获取服务项目单价 + ActionResult GetServiceProjectPrice(int ServiceProjectId)
        public ActionResult GetServiceProjectPrice(int ServiceProjectId)
        {
            var item = ServiceFactory.ServiceProjectServiceInstance.LoadByID(ServiceProjectId);
            if (item == null)
                return Content("");
            else
                return Content(item.Price.ToString());
        }
        #endregion

        #region 获取服务类型下面的服务项目 + JsonResult GetServiceProject(byte serviceProductType)
        /// <summary>
        /// 获取服务类型下面的服务项目
        /// </summary>
        /// <param name="serviceProductType"></param>
        /// <returns></returns>
        public JsonResult GetServiceProject(byte serviceProductType)
        {
            var data = ServiceFactory.ServiceProjectServiceInstance.LoadEntities(t => t.ServiceProductType == serviceProductType)
                .Select(t => new
                {
                    t.ProjectName,
                    t.ID
                }).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}